package com.tyteam.apps.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.script.CompiledScript;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.quartz.JobPersistenceException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.Trigger.TriggerState;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.spi.JobStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.shuohe.entity.system.user.User;
import com.shuohe.util.easyuiBean.EasyUiDataGrid2;
import com.tyteam.apps.common.JsonResult;
import com.tyteam.apps.model.DynamicTask;
import com.tyteam.apps.service.DynamicTaskService;
import cn.hutool.json.JSONObject;

@Controller
@RequestMapping("dynamicTask")
public class DynamicTaskController {
/*
	private Logger logger = LoggerFactory.getLogger(ProcessController.class);

	*//**
	 * 注入任务调度器
	 *//*
	@Autowired
	private Scheduler scheduler;
	*//**
	 * 调度器工厂类，用以查询可调度的任务
	 *//*
	@Autowired
	private SchedulerFactoryBean SchedulerFactoryBean;

	@Autowired(required = false)
	private DynamicTaskService dynamicTaskService;

	*//**
	 * 定时任务列表页面
	 * 
	 * @return
	 *//*
	@RequestMapping("")
	public ModelAndView index() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("dynamicTask/dynamicTaskList");
		return mv;
	}

	*//**
	 * 获取定时任务分页列表数据
	 * 
	 * @param request
	 * @param response
	 * @return
	 *//*
	@RequestMapping("getList")
	@ResponseBody
	public EasyUiDataGrid2 getList(HttpServletRequest request, HttpServletResponse response) {
		User user = (User) request.getSession().getAttribute("user");
		String activitiUUID = user.getActiviti_uuid();
		String _page = request.getParameter("page");
		String _rows = request.getParameter("rows");
		int currentpage = Integer.parseInt(_page);
		int rows = Integer.parseInt(_rows);
		Page<DynamicTask> page = new Page(currentpage, rows, "create_time",false);
		page = dynamicTaskService.selectPage(page);
		List<DynamicTask> list = page.getRecords();
		long count = list.size();
		return new EasyUiDataGrid2(count, list);
	};

	*//**
	 * 新增定时任务页面
	 * 
	 * @return
	 *//*
	@RequestMapping("add")
	public ModelAndView add() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("dynamicTask/addDynamicTask");
		return mv;
	}

	*//**
	 * 设置新的定时任务
	 * 
	 * @param dynamicTask
	 * @return
	 * @throws ClassNotFoundException 
	 * @throws SchedulerException 
	 *//*
	@RequestMapping("addOrUpdate")
	@ResponseBody
	public JsonResult setNewTask(String dynamicTask, HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SchedulerException {
		User user = (User) request.getSession().getAttribute("user");
		JsonResult result = new JsonResult();
		JSONObject str1 = new JSONObject(dynamicTask);
		DynamicTask param = str1.toBean(DynamicTask.class, false);
		DynamicTask params = new DynamicTask();
		String id = UUID.randomUUID().toString() + param.getTaskName();
		param.setId(id);
		param.setCreateBy(user.getId());
		param.setCreateTime(new Date());
		param.setUpdateBy(user.getId());
		param.setUpdateTime(new Date());
		dynamicTaskService.insertOrUpdate(param);
		result.setMsg("数据插入成功");
		result.setStatus("0");
		return result;
	}
	*//**
	 * 启动一个任务，传入参数为任务时间设置和类名()
	 * 
	 * @param startAtTime
	 * @param className
	 * @return
	 * @throws Exception
	 *//*
	@RequestMapping("startATask")
	@ResponseBody
	@Deprecated
	public JsonResult startATask(String taskName, String startTime, String className) throws Exception {
		JsonResult result = new JsonResult();
		// 任务名称
		String name = UUID.randomUUID().toString() + taskName;
		try {
			Class thisClass = Class.forName(className);
			// 任务所属分组
			String group = thisClass.getName();
			// 创建任务
			@SuppressWarnings("unchecked")
			JobDetail jobDetail = JobBuilder.newJob(thisClass).withIdentity(name, group).build();
			TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
			// 触发器名,触发器组
			triggerBuilder.withIdentity(name, group);
			// 触发器时间设定
			triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(startTime));
			// triggerBuilder.startNow();
			// 创建Trigger对象
			CronTrigger trigger = (CronTrigger) triggerBuilder.build();
			// 调度容器设置JobDetail和Trigger
			scheduler.scheduleJob(jobDetail, trigger);
			// // 启动
			// if (!scheduler.isShutdown()) {
			// scheduler.start();
			// }
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		result.setMsg("任务创建成功插入成功");
		result.setStatus("0");
		return result;
	}

	*//**
	 * 創建并啟動任務，如果任務已存在，則更新并啟動
	 * 
	 * @param taskName
	 * @param taskGroup
	 * @param startTime
	 * @param className
	 * @return
	 * @throws Exception
	 *//*
	@RequestMapping("createAndStart")
	@ResponseBody
	public JsonResult createAndStart(String id,String taskName, String taskGroup, String startTime, String className)
			throws Exception {
		JsonResult result = new JsonResult();
		Class thisClass = Class.forName(className);
		// schedulerFactoryBean 由spring创建注入
		Scheduler scheduler = SchedulerFactoryBean.getScheduler();
		// 这里获取任务信息数据
		TriggerKey triggerKey = TriggerKey.triggerKey(taskName, taskGroup);
		// 获取trigger，即在spring配置文件中定义的 bean id="myTrigger"
		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
		// 不存在，创建一个
		if (null == trigger) {
			JobDetail jobDetail = JobBuilder.newJob(thisClass).withIdentity(taskName, taskGroup).build();
			// jobDetail.getJobDataMap().put("scheduleJob", job);
			// 表达式调度构建器
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(startTime);
			// 按新的cronExpression表达式构建一个新的trigger
			trigger = TriggerBuilder.newTrigger().withIdentity(taskName, taskGroup).withSchedule(scheduleBuilder)
					.build();
			scheduler.scheduleJob(jobDetail, trigger);
			if (!scheduler.isShutdown()) {
				scheduler.start();
			}
		} else {
			// Trigger已存在，那么更新相应的定时设置
			// 表达式调度构建器
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(startTime);
			// 按新的cronExpression表达式重新构建trigger
			trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
			// 按新的trigger重新设置job执行
			scheduler.rescheduleJob(triggerKey, trigger);
			if (!scheduler.isShutdown()) {
				scheduler.start();
			}
		}
		DynamicTask dt = dynamicTaskService.selectById(id);
		dt.setId(id);
		dt.setState("1");
		dynamicTaskService.insertOrUpdate(dt);
		result.setStatus("0");
		result.setMsg("任务启动成功");
		return result;
	}
	
	@RequestMapping("plan")
	@ResponseBody
	public ModelAndView planList() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/dynamicTask/planTaskList");
		return mv;
	}
	// 计划中的任务
	*//**
	 * 计划中未启动的任务
	 * 
	 * @return
	 * @throws SchedulerException
	 *//*
	@RequestMapping("getPlanJobList")
	@ResponseBody
	public EasyUiDataGrid2 getJobList() throws SchedulerException {
		Scheduler scheduler = SchedulerFactoryBean.getScheduler();
		GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
		Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
		List<DynamicTask> jobList = new ArrayList<DynamicTask>();
		for (JobKey jobKey : jobKeys) {
			List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
			for (Trigger trigger : triggers) {
				DynamicTask job = new DynamicTask();
				job.setTaskName(jobKey.getName());
				job.setTaskGroup(jobKey.getGroup());
				job.setDescription("触发器:" + trigger.getKey());
				Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
				job.setState(triggerState.name());
				if (trigger instanceof CronTrigger) {
					CronTrigger cronTrigger = (CronTrigger) trigger;
					String cronExpression = cronTrigger.getCronExpression();
					job.setSchedulingPattern(cronExpression);
				}
				jobList.add(job);
			}
		}
		return new EasyUiDataGrid2(jobList.size(), jobList);
	}
	
	
	@RequestMapping("running")
	@ResponseBody
	public ModelAndView runningList() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/dynamicTask/runningTaskList");
		return mv;
	}
	*//**
	 * 查询已启动的任务
	 * 
	 * @param context
	 * @return
	 * @throws SchedulerException
	 *//*
	@RequestMapping("getRunningJobList")
	@ResponseBody
	public EasyUiDataGrid2 getRunningJobList(JobExecutionContext context) throws SchedulerException {
		JsonResult result = new JsonResult();
		Scheduler scheduler = SchedulerFactoryBean.getScheduler();
		if (null == scheduler) {
			System.out.println("取出空的");
		}
		List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
		List<DynamicTask> jobList = new ArrayList<DynamicTask>(executingJobs.size());
		for (JobExecutionContext executingJob : executingJobs) {
			DynamicTask job = new DynamicTask();
			JobDetail jobDetail = executingJob.getJobDetail();
			JobKey jobKey = jobDetail.getKey();
			Trigger trigger = executingJob.getTrigger();
			job.setTaskName(jobKey.getName());
			job.setTaskGroup(jobKey.getGroup());
			job.setDescription("触发器:" + trigger.getKey());
			Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
			job.setState(triggerState.name());
			if (trigger instanceof CronTrigger) {
				CronTrigger cronTrigger = (CronTrigger) trigger;
				String cronExpression = cronTrigger.getCronExpression();
				job.setSchedulingPattern(cronExpression);
			}
			jobList.add(job);
		}
		return new EasyUiDataGrid2(jobList.size(), jobList);
	}
	*//**
	 * 暂停任务
	 * @param taskName
	 * @param group
	 * @return
	 *//*
	@RequestMapping(value="/pause", method={RequestMethod.POST}) 
	@ResponseBody
	public JsonResult pause(String taskName,String taskGroup) {
		JsonResult result = new JsonResult();
		Scheduler scheduler = SchedulerFactoryBean.getScheduler();
		JobKey jobKey = JobKey.jobKey(taskName, taskGroup);
		TriggerKey triggerKey = TriggerKey.triggerKey(taskName, taskGroup);
		try {
			scheduler.pauseJob(jobKey);
			TriggerState state = scheduler.getTriggerState(triggerKey);
			int sta = state.ordinal();
			result.setObj(sta);
			result.setStatus("0");
			result.setMsg("任务暂停成功");
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	*//**
	 * 恢复任务
	 * @param taskName
	 * @param group
	 * @return
	 *//*
	@RequestMapping(value="/resume", method={RequestMethod.POST}) 
	@ResponseBody
	public JsonResult resume(String taskName,String taskGroup) {
		JsonResult result = new JsonResult();
		Scheduler scheduler = SchedulerFactoryBean.getScheduler();
		JobKey jobKey = JobKey.jobKey(taskName, taskGroup);
		TriggerKey triggerKey = TriggerKey.triggerKey(taskName, taskGroup);
		try {
			scheduler.resumeJob(jobKey);
			TriggerState state = scheduler.getTriggerState(triggerKey);
			int sta = state.ordinal();
			result.setObj(sta);
			result.setStatus("0");
			result.setMsg("任务恢复成功");
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return result;
	}
	*//**
	 * 删除任务/停止任务
	 * @param taskName
	 * @param group
	 * @return
	 *//*
	@RequestMapping(value="/delete", method={RequestMethod.POST}) 
	@ResponseBody
	public JsonResult delete(String id,String taskName,String taskGroup) {
		JsonResult result = new JsonResult();
		Scheduler scheduler = SchedulerFactoryBean.getScheduler();
		TriggerKey triggerKey = TriggerKey.triggerKey(taskName, taskGroup);
		JobKey jobKey = JobKey.jobKey(taskName, taskGroup);
		
		try {
			scheduler.pauseTrigger(triggerKey);// 停止触发器  
			scheduler.unscheduleJob(triggerKey);// 移除触发器  
			scheduler.deleteJob(jobKey);// 删除任务  
			DynamicTask dt = dynamicTaskService.selectById(id);
			dt.setId(id);
			dt.setState("0");
			dynamicTaskService.insertOrUpdate(dt);
			result.setStatus("0");
			result.setMsg("任务删除成功");
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		
		return result;
	}
*/
}
